******************
**** Figure 6 ****
******************

use "$data/paymentdata_ready" , clear


replace t=t+12

 forval i = 1(1)24  {
 bysort customer: egen cumulpayment`i'=sum(payment) if t <=`i' & t>=1
 bysort customer: egen cumulinvoice`i'=sum(invoice) if t <=`i' & t>=1
 winsor cumulinvoice`i', gen(cumulinvoice`i'w1) p(0.01)
winsor cumulpayment`i', gen(cumulpayment`i'w1) p(0.01)
 }
 
gen accumulatedpayment=.
gen accumulatedinvoice=.

forval i = 1(1)24  {
replace accumulatedpayment=cumulpayment`i'w1 if t==`i'
replace accumulatedinvoice=cumulinvoice`i'w1 if t==`i'
}
replace accumulatedpayment=0 if accumulatedpayment==.
replace accumulatedinvoice=0 if accumulatedinvoice==.



gen tilgung=accumulatedinvoice-accumulatedpayment


bysort treatmentidentity: egen pretreatmentmean2=mean(tilgung) if t<=12 // center around pre-treatment tilgung
bysort treatmentidentity: egen pretreatmentmean=mean(pretreatmentmean2)

bysort treatmentidentity: gen endpoint2=tilgung-pretreatmentmean if t==12 // center around intervention start
bysort treatmentidentity: egen endpoint=mean(endpoint2)


replace t=t-12
bysort treatmentidentity t: gen line=tilgung
collapse (mean) line pretreatmentmean endpoint, by(treatmentidentity t)
tabulate treatmentidentity, gen(g)

replace line=line-pretreatmentmean-endpoint

gen Untreated=g1*line if treatmentidentity==0
gen Basic=g2*line if treatmentidentity==1
gen PIDA=g3*line if treatmentidentity==2
gen NIDA=g4*line if treatmentidentity==3

line Untreated Basic PIDA NIDA t, ylabel(-8(2)8) ytitle("Debt Accumulation (Invoice-Payment)") xtitle("") yscale(r(-5 3)) legend(col(4)) title(Debt accumulation since intervention start, color(black)) graphregion(color(white)) xline(0, lwidth(tiny)) 
graph export "$filepath/output_logs/figure 6.pdf", replace


